#include <3ds.h>
#include "miscdef.h"
#include "MCU/Mcu.h"
#include <stdlib.h>
#include <stdio.h>

bool m_isSleeping = false;
bool m_oldIsSleeping = false;

u32 m_titleCount = 0;
u32 m_oldTitleCount = 0;

void calculateTitleCount()
{
	// Temp storage vars
	u32 titleCountSD = 0;
	u32 titleCountNAND = 0;
	// Reset m_titleCount
	m_titleCount = 0;

	// Init the AM service
	amInit();

	// Get the count of pending titles (sleep mode downloads) for SD (3DS Titles)
	AM_GetTitleCount(MEDIATYPE_SD, &titleCountSD);
	// Get the count of pending titles (sleep mode downloads) for NAND (TWL Titles)
	AM_GetTitleCount(MEDIATYPE_NAND, &titleCountNAND);

	// Exit the AM service
	amExit();

	// Add the values to m_titleCount
	m_titleCount += titleCountNAND;
	m_titleCount += titleCountSD;
}

int main()
{
	// Reset the RGB LED and blink with a white color
	ledReset();
	ledBlinkOnce(0xFFFFFF);

	// Calculate the title count at the beginning to set m_oldTitleCount
	calculateTitleCount();
	m_oldTitleCount = m_titleCount;

	while (true) {
		// Check if the shell is opened or closed via the MCU register
		u8 shellState = 0;
		mcuInit();
		mcuReadRegister(0x0F, &shellState, sizeof(shellState));
		mcuExit();
		shellState &= 2;

		// Store the old value in a variable
		m_oldIsSleeping = m_isSleeping;
		// Check if the shell is opened (shellState == 2) or the shell is closed (shellState == 0)
		if (shellState == 0)
			m_isSleeping = true;
		else
			m_isSleeping = false;

		// If the shell has been opened, reset the LED
		if (m_isSleeping != m_oldIsSleeping)
			if (!m_isSleeping && m_oldIsSleeping)
				ledReset();

		if (m_isSleeping) {
			// Store the old title count in a variable
			m_oldTitleCount = m_titleCount;

			// Get the actual title count
			calculateTitleCount();

			if (m_titleCount > m_oldTitleCount)
				ledBlinkThrice(0x19A4FF);
		}

		svcSleepThread(1e7);
	}
}
